package com.xinchuang.utils;

import cn.hutool.core.io.FileUtil;
import com.google.gson.Gson;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;


/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2023/9/20 10:57
 */
public class CommonUtil {

    public static boolean getImage(String inputFile, String outputFile) {
        try {
            int width = 0;
            int height = 0;
            BufferedImage image = ImageIO.read(FileUtil.newFile(inputFile));
            width = image.getWidth();
            height = image.getHeight();
            return generateThumbnail(inputFile, outputFile, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getUserId() {
        //从请求的头部获取userId
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String userId = request.getHeader("Id");
        return userId;
    }

    public static boolean generateThumbnail(String inputFile, String outputFile, int targetWidth, int targetHeight) {
        try {
            // 读取原始图像
            BufferedImage originalImage = ImageIO.read(new File(inputFile));

            // 计算缩略图的宽高比例
            double aspectRatio = (double) originalImage.getWidth() / originalImage.getHeight();
            int scaledWidth, scaledHeight;
            if (aspectRatio > 1) {
                scaledWidth = targetWidth;
                scaledHeight = (int) (targetWidth / aspectRatio);
            } else {
                scaledWidth = (int) (targetHeight * aspectRatio);
                scaledHeight = targetHeight;
            }

            // 创建缩略图
            BufferedImage thumbnailImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = thumbnailImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
            g2d.dispose();
            File file = new File(outputFile);
            FileUtil.mkdir(file.getParent());
            // 保存缩略图
            ImageIO.write(thumbnailImage, "JPEG", new File(outputFile));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isDouble(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

}
